package net.event.data_processing.utils;

import org.apache.jena.atlas.io.IndentedWriter;
import org.apache.jena.graph.Triple;
import org.apache.jena.query.*;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.sparql.core.Prologue;
import org.apache.jena.sparql.core.Var;
import org.apache.jena.sparql.syntax.ElementGroup;
import org.apache.jena.util.FileManager;
import org.apache.jena.vocabulary.DC;

import java.io.InputStream;

public class DataReader {
    public static Model readTTL(String inputFileName) {
        Model model = ModelFactory.createDefaultModel();
        InputStream in = FileManager.get().open(inputFileName);
        if(in == null)
            throw new IllegalArgumentException("File: "+inputFileName+" not found");
        model.read(in,"","TTL");
        return model;
    }
    
    
    public static void main(String[] args) {
//        String inputFileName = "data/source/yago/yagoSimpleTaxonomy_top_100.tsv";
//        Model model = ModelFactory.createDefaultModel();
//        InputStream in = FileManager.get().open(inputFileName);
//        if(in == null)
//            throw new IllegalArgumentException("File: "+inputFileName+" not found");
//        model.read(in,null);
        String inputFileName = "data/source/freebase/reified_top_100.ttl";
        Model model = readTTL(inputFileName);

        Prologue queryPrologue = new Prologue();
        queryPrologue.setPrefix("skos", "http://www.w3.org/2004/02/skos/core#");
        String sparql = "CONSTRUCT {\n" +
                " ?e a <http://framebase.org/ns/frame-Win_prize-win.v> . \n" +
                " ?e <http://framebase.org/ns/fe-Win_prize-Prize> ?o0 . \n" +
                " ?e <http://framebase.org/ns/fe-Win_prize-Competition> ?o1 . \n" +
                " ?e <http://framebase.org/ns/fe-Win_prize-Time> _:timePeriod . _:timePeriod a fmbs:frame-Timespan-period.n . _:timePeriod fmbs:fe-Timespan-Start ?o2 . _:timePeriod fmbs:fe-Timespan-End ?o2 . \n" +
                " ?e <http://framebase.org/ns/fe-Win_prize-Explanation> ?o3 . \n" +
                " ?e <http://framebase.org/ns/fe-Win_prize-Event_description> ?o4 . \n" +
                " ?e <http://framebase.org/ns/fe-Win_prize-Score> ?o5 . \n" +
                " ?e <http://framebase.org/ns/fe-Win_prize-Competitor> ?o6 . \n" +
                "} WHERE {\n" +
                " ?e a <http://rdf.freebase.com/ns/award.award_honor> . \n" +
                " OPTIONAL { ?e <http://rdf.freebase.com/ns/award.award_honor.award> ?o0 . } \n" +
                " OPTIONAL { ?e <http://rdf.freebase.com/ns/award.award_honor.ceremony> ?o1 . } \n" +
                " OPTIONAL { ?e <http://rdf.freebase.com/ns/award.award_honor.year> ?o2 . } \n" +
                " OPTIONAL { ?e <http://rdf.freebase.com/ns/award.award_honor.honored_for> ?o3 . } \n" +
                " OPTIONAL { ?e <http://rdf.freebase.com/ns/award.award_honor.notes_description> ?o4 . } \n" +
                " OPTIONAL { ?e <http://rdf.freebase.com/ns/award.award_honor.achievement_level> ?o5 . } \n" +
                " OPTIONAL { ?e <http://rdf.freebase.com/ns/award.award_honor.award_winner> ?o6 . } \n" +
                "} \n\n";
        Query query = QueryFactory.parse(new Query(queryPrologue), sparql, null, null);

        query.setQuerySelectType() ;
//
//        // Build pattern
//
//        ElementGroup elg = new ElementGroup() ;
//
//        Var varTitle = Var.alloc("title") ;
//        Var varX = Var.alloc("x") ;
//
//        Triple t1 = new Triple(varX, DC.title.asNode(),  varTitle) ;
//        elg.addTriplePattern(t1) ;
//
//        // Don't use bNodes for anon variables.  The conversion is done in parsing.
//        // BNodes here are assumed to be values from the target graph.
//        Triple t2 = new Triple(varX, DC.description.asNode(), Var.alloc("desc")) ;
//        elg.addTriplePattern(t2) ;
//
//        // Attach the group to query.  
//        query.setQueryPattern(elg) ;
//
//        // Choose what we want - SELECT *
//        //query.setQueryResultStar(true) ;
//        query.addResultVar(varTitle) ;
//
//        // Print query with line numbers
//        // Prefix mapping just helps serialization
//        query.getPrefixMapping().setNsPrefix("dc" , DC.getURI()) ;
//        query.serialize(new IndentedWriter(System.out,true)) ;
        System.out.println() ;

        try ( QueryExecution qexec = QueryExecutionFactory.create(query, model) ) {
            // Assumption: it's a SELECT query.
            ResultSet rs = qexec.execSelect() ;

            // The order of results is undefined.
            System.out.println("Titles: ") ;
            for ( ; rs.hasNext() ; )
            {
                QuerySolution rb = rs.nextSolution() ;

                // Get title - variable names do not include the '?' (or '$')
                RDFNode x = rb.get("title") ;

                // Check the type of the result value
                if ( x instanceof Literal)
                {
                    Literal titleStr = (Literal)x  ;
                    System.out.println("    "+titleStr) ;
                }
                else
                    System.out.println("Strange - not a literal: "+x) ;

            }
        }
    }
}
